package org.cuckoos.android.command;

import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;

import org.cuckoos.android.domain.Command;
import org.cuckoos.android.domain.Constant;
import org.cuckoos.android.domain.User;
import org.cuckoos.android.ui.AppActivity;


/**
 * 发送和处理进入消息
 * @author bugu
 *
 */
public class EntryCommand extends AbstractCommand {

	private Command command;
	public EntryCommand(DatagramSocket ds ,AppActivity activity){
		super(ds);
		this.activity = activity;
	}
	
	public EntryCommand(DatagramSocket ds ,User user){
		super(ds);
		command = new Command(user, Constant.IPMSG_BR_ENTRY);
	}
	
	@Override
	public void execute() {
		execute(command);
	}

	@Override
	public void handle(Command ac) {
		User newOne = ac.getUser();
		newOne.setIp(ac.getUser().getIp());
		getActivity().updateUserList(newOne);
		try {
			if(!ac.getUser().getHost().equals(InetAddress.getLocalHost().getHostName())){
				ansentry(ac);
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
	}
	
	private void ansentry(Command command) throws UnknownHostException{
		
		AnsentryCommand ac = new AnsentryCommand(ds,command);
		ac.execute();
	}

	@Override
	public boolean isHandle(Command ac) {
		return Constant.GET_MODE(ac.getCommand()) == Constant.IPMSG_BR_ENTRY;
		
	}
	
private AppActivity activity;
	
	public AppActivity getActivity() {
		return activity;
	}

	public void setActivity(AppActivity activity) {
		this.activity = activity;
	}

}
